
// 统一 API 前缀
const RESOURCE_API = '/api/courseResources';

/**
 * 获取某课程下的所有资源
 */
export const fetchCourseResources = async (courseId) => {
    if (!courseId) return [];
    try {
        const response = await api.get(`${RESOURCE_API}/course/${courseId}`);
        return response.data;
    } catch (error) {
        console.error('Error fetching course resources:', error);
        throw new Error('无法获取资源信息，请稍后重试。');
    }
};

/**
 * 上传新资源
 */
export const addCourseResource = async (resourceData) => {
    if (!resourceData || !resourceData.title || !resourceData.courseId) {
        throw new Error('资源信息不完整');
    }

    try {
        const response = await api.post(RESOURCE_API, resourceData);
        return response.data;
    } catch (error) {
        console.error('Error submitting form:', error);
        throw new Error('资源上传失败，请稍后重试。');
    }
};

/**
 * 更新已有资源
 */
export const updateCourseResource = async (resourceId, resourceData) => {
    if (!resourceId || !resourceData || !resourceData.title) {
        throw new Error('资源ID或内容缺失');
    }

    try {
        const response = await api.put(`${RESOURCE_API}/${resourceId}`, resourceData);
        return response.data;
    } catch (error) {
        console.error('Error updating course resource:', error);
        throw new Error('资源更新失败，请稍后重试。');
    }
};

/**
 * 删除指定资源
 */
export const deleteCourseResource = async (resourceId) => {
    if (!resourceId) throw new Error('缺少资源ID');

    try {
        await api.delete(`${RESOURCE_API}/${resourceId}`);
        return resourceId;
    } catch (error) {
        console.error('Error deleting course resource:', error);
        throw new Error('资源删除失败，请稍后重试。');
    }
};

/**
 * 获取资源关联的章节信息
 */
export const getResourceSections = async (resourceId) => {
    if (!resourceId) throw new Error('缺少资源ID');

    try {
        const response = await api.get(`${RESOURCE_API}/${resourceId}/sections`);
        return response.data;
    } catch (error) {
        console.error('Error fetching sections for resource:', error);
        throw new Error('无法加载章节信息，请稍后重试。');
    }
};